# !/usr/bin/env python3
# -*- coding: utf-8 -*-

'此模块负责数据可视化'

from jinja2 import Environment, FileSystemLoader, select_autoescape
import fs

from crown.leaf import template_dict
from crown.twig import (
    get_html_index,
    get_html_overall,
    get_js_index,
    get_js_overall
)


class Bough(object):
    """分配数据类

    根据模版分配数据

    Attributes:
        data_raw: pandas.DataFrame对象，待处理的数据
        __templates: tuple对象，包含html、js字符串
    """

    def __init__(self, data_raw) -> None:
        """类初始化"""
        self.__osfs = fs.open_fs('./')
        self.__templates = self.__bloom(*self.__dismember(data_raw))

    def __dismember(self, data_raw) -> tuple:
        """打散、分化数据

        将原始数据按照web模版的需要分化为不同的用来渲染模版的数据

        Args:
            data_raw: pandas.DataFrame对象，待处理的数据

        Returns:
            tuple: 一个tuple对象，分别为html及js文件模板渲染数据

        Raises:
            None
        """
        return (
            get_html_index(),
            get_html_overall(data_raw),
            get_js_index(),
            get_js_overall(data_raw)
        )

    def __bloom(self, *data_template) -> tuple:
        """渲染

        进行模版渲染

        Args:
            data_template: tuple对象，待处理的模版数据

        Returns:
            tuple: 所有html和js渲染后的模版字符串

        Raises:
            None
        """
        templates = []
        output = []
        env = Environment(
            loader=FileSystemLoader('./templates'),
            autoescape=select_autoescape(['html'])
        )
        span = len(data_template)
        for i in range(0, span):
            if self.__osfs.exists('{}/{}'.format('templates', template_dict['from'][i])): # noqa E501
                templates.append(env.get_template(template_dict['from'][i]))
            else:
                templates.append(None)

        for i in range(0, span):
            if templates[i] is None:
                output.append(None)
            else:
                output.append(templates[i].render(info=data_template[i]))
        return tuple(output)

    @property
    def templates(self) -> tuple:
        """对外只读属性接口"""
        return self.__templates
